home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / imap-3.0 / ANSI / c-client / bezerk.c next >
Encoding:
C/C++ Source or Header  |  1993-07-20  |  66.5 KB  |  2,080 lines

  1. /*
  2.  * Program:    Berkeley mail routines
  3.  *
  4.  * Author:    Mark Crispin
  5.  *        Networks and Distributed Computing
  6.  *        Computing & Communications
  7.  *        University of Washington
  8.  *        Administration Building, AG-44
  9.  *        Seattle, WA  98195
  10.  *        Internet: MRC@CAC.Washington.EDU
  11.  *
  12.  * Date:    20 December 1989
  13.  * Last Edited:    20 July 1993
  14.  *
  15.  * Copyright 1993 by the University of Washington
  16.  *
  17.  *  Permission to use, copy, modify, and distribute this software and its
  18.  * documentation for any purpose and without fee is hereby granted, provided
  19.  * that the above copyright notice appears in all copies and that both the
  20.  * above copyright notice and this permission notice appear in supporting
  21.  * documentation, and that the name of the University of Washington not be
  22.  * used in advertising or publicity pertaining to distribution of the software
  23.  * without specific, written prior permission.  This software is made
  24.  * available "as is", and
  25.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  26.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  27.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  28.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  29.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  30.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  31.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  32.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  33.  *
  34.  */
  35.  
  36.  
  37. /* Dedication:
  38.  *  This file is dedicated with affection to those Merry Marvels of Musical
  39.  * Madness . . .
  40.  *  ->  The Incomparable Leland Stanford Junior University Marching Band  <-
  41.  * who entertain, awaken, and outrage Stanford fans in the fact of repeated
  42.  * losing seasons and shattered Rose Bowl dreams [Cardinal just don't have
  43.  * HUSKY FEVER!!!].
  44.  *
  45.  */
  46.  
  47. #include <stdio.h>
  48. #include <ctype.h>
  49. #include <netdb.h>
  50. #include <errno.h>
  51. extern int errno;        /* just in case */
  52. #include <signal.h>
  53. #include "mail.h"
  54. #include "osdep.h"
  55. #include <pwd.h>
  56. #include <sys/file.h>
  57. #include <sys/stat.h>
  58. #include <sys/time.h>
  59. #include "bezerk.h"
  60. #include "rfc822.h"
  61. #include "misc.h"
  62.  
  63. /* Berkeley mail routines */
  64.  
  65.  
  66. /* Driver dispatch used by MAIL */
  67.  
  68. DRIVER bezerkdriver = {
  69.   "bezerk",            /* driver name */
  70.   (DRIVER *) NIL,        /* next driver */
  71.   bezerk_valid,            /* mailbox is valid for us */
  72.   bezerk_parameters,        /* manipulate parameters */
  73.   bezerk_find,            /* find mailboxes */
  74.   bezerk_find_bboards,        /* find bboards */
  75.   bezerk_find_all,        /* find all mailboxes */
  76.   bezerk_find_all_bboards,    /* find all bboards */
  77.   bezerk_subscribe,        /* subscribe to mailbox */
  78.   bezerk_unsubscribe,        /* unsubscribe from mailbox */
  79.   bezerk_subscribe_bboard,    /* subscribe to bboard */
  80.   bezerk_unsubscribe_bboard,    /* unsubscribe from bboard */
  81.   bezerk_create,        /* create mailbox */
  82.   bezerk_delete,        /* delete mailbox */
  83.   bezerk_rename,        /* rename mailbox */
  84.   bezerk_open,            /* open mailbox */
  85.   bezerk_close,            /* close mailbox */
  86.   bezerk_fetchfast,        /* fetch message "fast" attributes */
  87.   bezerk_fetchflags,        /* fetch message flags */
  88.   bezerk_fetchstructure,    /* fetch message envelopes */
  89.   bezerk_fetchheader,        /* fetch message header only */
  90.   bezerk_fetchtext,        /* fetch message body only */
  91.   bezerk_fetchbody,        /* fetch message body section */
  92.   bezerk_setflag,        /* set message flag */
  93.   bezerk_clearflag,        /* clear message flag */
  94.   bezerk_search,        /* search for message based on criteria */
  95.   bezerk_ping,            /* ping mailbox to see if still alive */
  96.   bezerk_check,            /* check for new messages */
  97.   bezerk_expunge,        /* expunge deleted messages */
  98.   bezerk_copy,            /* copy messages to another mailbox */
  99.   bezerk_move,            /* move messages to another mailbox */
  100.   bezerk_append,        /* append string message to mailbox */
  101.   bezerk_gc            /* garbage collect stream */
  102. };
  103.  
  104.                 /* prototype stream */
  105. MAILSTREAM bezerkproto = {&bezerkdriver};
  106.  
  107. /* Berkeley mail validate mailbox
  108.  * Accepts: mailbox name
  109.  * Returns: our driver if name is valid, NIL otherwise
  110.  */
  111.  
  112. DRIVER *bezerk_valid (char *name)
  113. {
  114.   char tmp[MAILTMPLEN];
  115.   return bezerk_isvalid (name,tmp) ? &bezerkdriver : NIL;
  116. }
  117.  
  118.  
  119. /* Berkeley mail test for valid mailbox
  120.  * Accepts: mailbox name
  121.  * Returns: T if valid, NIL otherwise
  122.  */
  123.  
  124. int bezerk_isvalid (char *name,char *tmp)
  125. {
  126.   int i,fd,ti,zn;
  127.   int ret = NIL;
  128.   char *s = tmp,*t;
  129.   struct stat sbuf;
  130.   struct hostent *host_name;
  131.   if (!lhostn) {        /* have local host yet? */
  132.     gethostname(tmp,MAILTMPLEN);/* get local host name */
  133.     lhostn = cpystr ((host_name = gethostbyname (tmp)) ?
  134.              host_name->h_name : tmp);
  135.   }
  136.                 /* INBOX is always accepted */
  137.   if (!strcmp (ucase (strcpy (tmp,name)),"INBOX")) return T;
  138.                 /* if file, get its status */
  139.   if ((*name != '{') && !((*name == '*') && (name[1] == '{')) &&
  140.       (stat (bezerk_file (tmp,name),&sbuf) == 0) &&
  141.       ((fd = open (tmp,O_RDONLY,NIL)) >= 0)) {
  142.     if (sbuf.st_size == 0) {     /* allow empty file if not .txt */
  143.       if ((i = strlen (tmp)) < 4 || strcmp (tmp + i - 4 ,".txt"))
  144.     return LONGT;
  145.     }
  146.     else if ((read (fd,tmp,MAILTMPLEN-1) >= 0) &&
  147.          (tmp[0] == 'F') && VALID (s,t,ti,zn)) ret = T;
  148.     close (fd);            /* close the file */
  149.   }
  150.   return ret;            /* return what we should */
  151. }
  152.  
  153. /* Berkeley manipulate driver parameters
  154.  * Accepts: function code
  155.  *        function-dependent value
  156.  * Returns: function-dependent return value
  157.  */
  158.  
  159. void *bezerk_parameters (long function,void *value)
  160. {
  161.   fatal ("Invalid bezerk_parameters function");
  162.   return NIL;
  163. }
  164.  
  165. /* Berkeley mail find list of mailboxes
  166.  * Accepts: mail stream
  167.  *        pattern to search
  168.  */
  169.  
  170. void bezerk_find (MAILSTREAM *stream,char *pat)
  171. {
  172.   void *s = NIL;
  173.   char *t,tmp[MAILTMPLEN];
  174.   while (t = sm_read (&s))    /* read subscription database */
  175.     if ((*t != '{') && (*t != '*') &&
  176.     strcmp (t,"INBOX") && pmatch (t,pat) && bezerk_isvalid (t,tmp))
  177.       mm_mailbox (t);
  178. }
  179.  
  180.  
  181. /* Berkeley mail find list of bboards
  182.  * Accepts: mail stream
  183.  *        pattern to search
  184.  */
  185.  
  186. void bezerk_find_bboards (MAILSTREAM *stream,char *pat)
  187. {
  188.   void *s = NIL;
  189.   char *t,tmp[MAILTMPLEN];
  190.   while (t = sm_read (&s))    /* read subscription database */
  191.     if ((*t == '*') && (t[1] != '{') &&
  192.     pmatch (t+1,pat) && bezerk_isvalid (t+1,tmp))
  193.       mm_bboard (t+1);
  194. }
  195.  
  196. /* Berkeley mail find list of all mailboxes
  197.  * Accepts: mail stream
  198.  *        pattern to search
  199.  */
  200.  
  201. void bezerk_find_all (MAILSTREAM *stream,char *pat)
  202. {
  203.   DIR *dirp;
  204.   struct direct *d;
  205.   char tmp[MAILTMPLEN],file[MAILTMPLEN];
  206.   int i = 0;
  207.   char *s,*t;
  208.   if (s = strrchr (pat,'/')) {    /* directory specified in pattern? */
  209.     strncpy (file,pat,i = (++s) - pat);
  210.     file[i] = '\0';        /* tie off prefix */
  211.     t = bezerk_file (tmp,pat);    /* make fully-qualified file name */
  212.                 /* tie off directory name */
  213.     if (s = strrchr (t,'/')) *s = '\0';
  214.   }
  215.   else t = myhomedir ();    /* use home directory to search */
  216.   if (dirp = opendir (t)) {    /* now open that directory */
  217.     while (d = readdir (dirp)) {/* for each directory entry */
  218.       strcpy (file + i,d->d_name);
  219.       if (pmatch (file,pat) && (bezerk_isvalid (file,tmp))) mm_mailbox (file);
  220.     }
  221.     closedir (dirp);        /* flush directory */
  222.   }
  223. }
  224.  
  225. /* Berkeley mail find list of all bboards
  226.  * Accepts: mail stream
  227.  *        pattern to search
  228.  */
  229.  
  230. void bezerk_find_all_bboards (MAILSTREAM *stream,char *pat)
  231. {
  232.   DIR *dirp;
  233.   struct direct *d;
  234.   struct passwd *pw;
  235.   char tmp[MAILTMPLEN],file[MAILTMPLEN];
  236.   int i = 1;
  237.   char *s;
  238.   if (!((pw = getpwnam ("ftp")) && pw->pw_dir)) return;
  239.   file[0] = '*';        /* bboard designator */
  240.                 /* directory specified in pattern? */
  241.   if (s = strrchr (pat,'/')) strncpy (file + 1,pat,i += (++s) - pat);
  242.   file[i] = '\0';        /* tie off prefix */
  243.   sprintf (tmp,"%s/%s",pw->pw_dir,(file[1] == '/') ? file + 2 : file + 1);
  244.   if (dirp = opendir (tmp)) {    /* now open that directory */
  245.     while (d = readdir (dirp)) {/* for each directory entry */
  246.       strcpy (file + i,d->d_name);
  247.       if (pmatch (file + 1,pat) && (bezerk_isvalid (file,tmp)))
  248.     mm_bboard (file + 1);
  249.     }
  250.     closedir (dirp);        /* flush directory */
  251.   }
  252. }
  253.  
  254. /* Berkeley mail subscribe to mailbox
  255.  * Accepts: mail stream
  256.  *        mailbox to add to subscription list
  257.  * Returns: T on success, NIL on failure
  258.  */
  259.  
  260. long bezerk_subscribe (MAILSTREAM *stream,char *mailbox)
  261. {
  262.   char tmp[MAILTMPLEN];
  263.   return sm_subscribe (bezerk_file (tmp,mailbox));
  264. }
  265.  
  266.  
  267. /* Berkeley mail unsubscribe to mailbox
  268.  * Accepts: mail stream
  269.  *        mailbox to delete from subscription list
  270.  * Returns: T on success, NIL on failure
  271.  */
  272.  
  273. long bezerk_unsubscribe (MAILSTREAM *stream,char *mailbox)
  274. {
  275.   char tmp[MAILTMPLEN];
  276.   return sm_unsubscribe (bezerk_file (tmp,mailbox));
  277. }
  278.  
  279.  
  280. /* Berkeley mail subscribe to bboard
  281.  * Accepts: mail stream
  282.  *        bboard to add to subscription list
  283.  * Returns: T on success, NIL on failure
  284.  */
  285.  
  286. long bezerk_subscribe_bboard (MAILSTREAM *stream,char *mailbox)
  287. {
  288.   return NIL;            /* never valid for Bezerk */
  289. }
  290.  
  291.  
  292. /* Berkeley mail unsubscribe to bboard
  293.  * Accepts: mail stream
  294.  *        bboard to delete from subscription list
  295.  * Returns: T on success, NIL on failure
  296.  */
  297.  
  298. long bezerk_unsubscribe_bboard (MAILSTREAM *stream,char *mailbox)
  299. {
  300.   return NIL;            /* never valid for Bezerk */
  301. }
  302.  
  303. /* Berkeley mail create mailbox
  304.  * Accepts: MAIL stream
  305.  *        mailbox name to create
  306.  * Returns: T on success, NIL on failure
  307.  */
  308.  
  309. long bezerk_create (MAILSTREAM *stream,char *mailbox)
  310. {
  311.   char tmp[MAILTMPLEN];
  312.   int i,fd;
  313.                 /* must be a ".txt" file */
  314.   if ((i = strlen (mailbox)) > 4 && !strcmp (mailbox + i - 4 ,".txt")) {
  315.     mm_log ("Can't create mailbox: name must not end with .txt",ERROR);
  316.     return NIL;
  317.   }
  318.   if ((fd = open (bezerk_file (tmp,mailbox),O_WRONLY|O_CREAT|O_EXCL,0600))<0) {
  319.     sprintf (tmp,"Can't create mailbox %s: %s",mailbox,strerror (errno));
  320.     mm_log (tmp,ERROR);
  321.     return NIL;
  322.   }
  323.   close (fd);            /* close the file */
  324.   return T;            /* return success */
  325. }
  326.  
  327.  
  328. /* Berkeley mail delete mailbox
  329.  * Accepts: MAIL stream
  330.  *        mailbox name to delete
  331.  * Returns: T on success, NIL on failure
  332.  */
  333.  
  334. long bezerk_delete (MAILSTREAM *stream,char *mailbox)
  335. {
  336.   return bezerk_rename (stream,mailbox,NIL);
  337. }
  338.  
  339. /* Berkeley mail rename mailbox
  340.  * Accepts: MAIL stream
  341.  *        old mailbox name
  342.  *        new mailbox name (or NIL for delete)
  343.  * Returns: T on success, NIL on failure
  344.  */
  345.  
  346. long bezerk_rename (MAILSTREAM *stream,char *old,char *new)
  347. {
  348.   long ret = T;
  349.   char tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN],lockx[MAILTMPLEN];
  350.   int fd,ld;
  351.                 /* get the c-client lock */
  352.   if ((ld = open (lockname (lock,bezerk_file (file,old)),O_RDWR|O_CREAT,0666))
  353.       < 0) {
  354.     sprintf (tmp,"Can't get lock for mailbox %s: %s",old,strerror (errno));
  355.     mm_log (tmp,ERROR);
  356.     return NIL;
  357.   }
  358.                 /* lock out other c-clients */
  359.   if (flock (ld,LOCK_EX|LOCK_NB)) {
  360.     close (ld);            /* couldn't lock, give up on it then */
  361.     sprintf (tmp,"Mailbox %s is in use by another process",old);
  362.     mm_log (tmp,ERROR);
  363.     return NIL;
  364.   }
  365.                 /* lock out non c-client applications */
  366.   if ((fd = bezerk_lock (file,O_RDONLY,S_IREAD|S_IWRITE,lockx,LOCK_EX)) < 0) {
  367.     sprintf (tmp,"Can't lock mailbox %s: %s",old,strerror (errno));
  368.     mm_log (tmp,ERROR);
  369.     return NIL;
  370.   }
  371.                 /* do the rename or delete operation */
  372.   if (new ? rename (file,bezerk_file (tmp,new)) : unlink (file)) {
  373.     sprintf (tmp,"Can't %s mailbox %s: %s",new ? "rename" : "delete",old,
  374.          strerror (errno));
  375.     mm_log (tmp,ERROR);
  376.     ret = NIL;            /* set failure */
  377.   }
  378.   bezerk_unlock (fd,NIL,lockx);    /* unlock and close mailbox */
  379.   flock (ld,LOCK_UN);        /* release c-client lock lock */
  380.   close (ld);            /* close c-client lock */
  381.   unlink (lock);        /* and delete it */
  382.   return ret;            /* return success */
  383. }
  384.  
  385. /* Berkeley mail open
  386.  * Accepts: Stream to open
  387.  * Returns: Stream on success, NIL on failure
  388.  */
  389.  
  390. MAILSTREAM *bezerk_open (MAILSTREAM *stream)
  391. {
  392.   long i;
  393.   long retry = KODRETRY;    /* number of seconds to retry */
  394.   int fd;
  395.   char tmp[MAILTMPLEN];
  396.   struct stat sbuf;
  397.                 /* return prototype for OP_PROTOTYPE call */
  398.   if (!stream) return &bezerkproto;
  399.   if (LOCAL) {            /* close old file if stream being recycled */
  400.     bezerk_close (stream);    /* dump and save the changes */
  401.     stream->dtb = &bezerkdriver;/* reattach this driver */
  402.     mail_free_cache (stream);    /* clean up cache */
  403.   }
  404.   stream->local = fs_get (sizeof (BEZERKLOCAL));
  405.                 /* canonicalize the stream mailbox name */
  406.   bezerk_file (tmp,stream->mailbox);
  407.                 /* force readonly if bboard */
  408.   if (*stream->mailbox == '*') stream->readonly = T;
  409.   else {            /* canonicalize name */
  410.     fs_give ((void **) &stream->mailbox);
  411.     stream->mailbox = cpystr (tmp);
  412.   }
  413.   /* You may wonder why LOCAL->name is needed.  It isn't at all obvious from
  414.    * the code.  The problem is that when a stream is recycled with another
  415.    * mailbox of the same type, the driver's close method isn't called because
  416.    * it could be IMAP and closing then would defeat the entire point of
  417.    * recycling.  Hence there is code in the file drivers to call the close
  418.    * method such as what appears above.  The problem is, by this point,
  419.    * mail_open() has already changed the stream->mailbox name to point to the
  420.    * new name, and bezerk_close() needs the old name.
  421.    */
  422.   LOCAL->name = cpystr (tmp);    /* local copy for recycle case */
  423.                 /* build name of our lock file */
  424.   LOCAL->lname = cpystr (lockname (tmp,LOCAL->name));
  425.   LOCAL->ld = NIL;        /* no state locking yet */
  426.   LOCAL->filesize = 0;        /* initialize file information */
  427.   LOCAL->filetime = 0;
  428.   LOCAL->msgs = NIL;        /* no cache yet */
  429.   LOCAL->cachesize = 0;
  430.   LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNK) + 1);
  431.   stream->sequence++;        /* bump sequence number */
  432.  
  433.   LOCAL->dirty = NIL;        /* no update yet */
  434.                 /* make lock for read/write access */
  435.   if (!stream->readonly) while (retry) {
  436.                 /* get a new file handle each time */
  437.     if ((fd = open (LOCAL->lname,O_RDWR|O_CREAT,0666)) < 0)
  438.       mm_log ("Can't open mailbox lock, access is readonly",WARN);
  439.                 /* can get the lock? */
  440.     if (flock (fd,LOCK_EX|LOCK_NB)) {
  441.       if (retry-- == KODRETRY) {/* no, first time through? */
  442.                 /* yes, get other process' PID */
  443.     if (!fstat (fd,&sbuf) && (i = min (sbuf.st_size,MAILTMPLEN)) &&
  444.         (read (fd,tmp,i) == i) && (i = atol (tmp))) {
  445.       kill (i,SIGUSR2);    /* send the Kiss Of Death */
  446.       sprintf (tmp,"Trying to get mailbox lock from process %ld",i);
  447.       mm_log (tmp,WARN);
  448.     }
  449.     else retry = 0;        /* give up */
  450.       }
  451.       close (fd);        /* get a new handle next time around */
  452.       if (retry) sleep (1);    /* wait a second before trying again */
  453.       else mm_log ("Mailbox is open by another process, access is readonly",
  454.            WARN);
  455.     }
  456.     else {            /* got the lock, nobody else can alter state */
  457.       LOCAL->ld = fd;        /* note lock's fd */
  458.       chmod (LOCAL->lname,0666);/* make sure mode OK (don't use fchmod()) */
  459.                 /* note our PID in the lock */
  460.       sprintf (tmp,"%d",getpid ());
  461.       write (fd,tmp,(i = strlen (tmp))+1);
  462.       ftruncate (fd,i);        /* make sure tied off */
  463.       fsync (fd);        /* make sure it's available */
  464.       retry = 0;        /* no more need to try */
  465.     }
  466.   }
  467.  
  468.                 /* parse mailbox */
  469.   stream->nmsgs = stream->recent = 0;
  470.                 /* will we be able to get write access? */
  471.   if (LOCAL->ld && access (LOCAL->name,W_OK) && (errno == EACCES)) {
  472.     mm_log ("Can't get write access to mailbox, access is readonly",WARN);
  473.     flock (LOCAL->ld,LOCK_UN);    /* release the lock */
  474.     close (LOCAL->ld);        /* close the lock file */
  475.     LOCAL->ld = NIL;        /* no more lock fd */
  476.     unlink (LOCAL->lname);    /* delete it */
  477.     fs_give ((void **) &LOCAL->lname);
  478.   }
  479.                 /* parse mailbox */
  480.   if ((fd = bezerk_parse (stream,tmp,LOCK_SH)) >= 0) {
  481.     bezerk_unlock (fd,stream,tmp);
  482.     mail_unlock (stream);
  483.   }
  484.   if (!LOCAL) return NIL;    /* failure if stream died */
  485.   stream->readonly = !LOCAL->ld;/* make sure upper level knows readonly */
  486.                 /* notify about empty mailbox */
  487.   if (!(stream->nmsgs || stream->silent)) mm_log ("Mailbox is empty",NIL);
  488.   return stream;        /* return stream alive to caller */
  489. }
  490.  
  491. /* Berkeley mail close
  492.  * Accepts: MAIL stream
  493.  */
  494.  
  495. void bezerk_close (MAILSTREAM *stream)
  496. {
  497.   int fd;
  498.   int silent = stream->silent;
  499.   char lock[MAILTMPLEN];
  500.   if (LOCAL && LOCAL->ld) {    /* is stream alive? */
  501.     stream->silent = T;        /* note this stream is dying */
  502.                 /* lock mailbox and parse new messages */
  503.     if (LOCAL->dirty && (fd = bezerk_parse (stream,lock,LOCK_EX)) >= 0) {
  504.                 /* dump any changes not saved yet */
  505.       if (bezerk_extend    (stream,fd,"Close failed to update mailbox"))
  506.     bezerk_save (stream,fd);
  507.                 /* flush locks */
  508.       bezerk_unlock (fd,stream,lock);
  509.       mail_unlock (stream);
  510.     }
  511.     stream->silent = silent;    /* restore previous status */
  512.   }
  513.   bezerk_abort (stream);    /* now punt the file and local data */
  514. }
  515.  
  516.  
  517. /* Berkeley mail fetch fast information
  518.  * Accepts: MAIL stream
  519.  *        sequence
  520.  */
  521.  
  522. void bezerk_fetchfast (MAILSTREAM *stream,char *sequence)
  523. {
  524.   return;            /* no-op for local mail */
  525. }
  526.  
  527.  
  528. /* Berkeley mail fetch flags
  529.  * Accepts: MAIL stream
  530.  *        sequence
  531.  */
  532.  
  533. void bezerk_fetchflags (MAILSTREAM *stream,char *sequence)
  534. {
  535.   return;            /* no-op for local mail */
  536. }
  537.  
  538. /* Berkeley mail fetch structure
  539.  * Accepts: MAIL stream
  540.  *        message # to fetch
  541.  *        pointer to return body
  542.  * Returns: envelope of this message, body returned in body value
  543.  *
  544.  * Fetches the "fast" information as well
  545.  */
  546.  
  547. ENVELOPE *bezerk_fetchstructure (MAILSTREAM *stream,long msgno,BODY **body)
  548. {
  549.   ENVELOPE **env;
  550.   BODY **b;
  551.   STRING bs;
  552.   LONGCACHE *lelt;
  553.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  554.   long i = max (m->headersize,m->bodysize);
  555.   if (stream->scache) {        /* short cache */
  556.     if (msgno != stream->msgno){/* flush old poop if a different message */
  557.       mail_free_envelope (&stream->env);
  558.       mail_free_body (&stream->body);
  559.     }
  560.     stream->msgno = msgno;
  561.     env = &stream->env;        /* get pointers to envelope and body */
  562.     b = &stream->body;
  563.   }
  564.   else {            /* long cache */
  565.     lelt = mail_lelt (stream,msgno);
  566.     env = &lelt->env;        /* get pointers to envelope and body */
  567.     b = &lelt->body;
  568.   }
  569.   if ((body && !*b) || !*env) {    /* have the poop we need? */
  570.     mail_free_envelope (env);    /* flush old envelope and body */
  571.     mail_free_body (b);
  572.     if (i > LOCAL->buflen) {    /* make sure enough buffer space */
  573.       fs_give ((void **) &LOCAL->buf);
  574.       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = i) + 1);
  575.     }
  576.     INIT (&bs,mail_string,(void *) m->body,m->bodysize);
  577.                 /* parse envelope and body */
  578.     rfc822_parse_msg (env,body ? b : NIL,m->header,m->headersize,&bs,lhostn,
  579.               LOCAL->buf);
  580.   }
  581.   if (body) *body = *b;        /* return the body */
  582.   return *env;            /* return the envelope */
  583. }
  584.  
  585. /* Berkeley mail snarf message, only for Tenex driver
  586.  * Accepts: MAIL stream
  587.  *        message # to snarf
  588.  *        pointer to size to return
  589.  * Returns: message text in RFC822 format
  590.  */
  591.  
  592. char *bezerk_snarf (MAILSTREAM *stream,long msgno,long *size)
  593. {
  594.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  595.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  596.   if (((*size = m->headersize + m->bodysize) > LOCAL->buflen) ||
  597.       LOCAL->buflen > CHUNK) {    /* make sure stream can hold the text */
  598.                 /* fs_resize would do an unnecessary copy */
  599.     fs_give ((void **) &LOCAL->buf);
  600.     LOCAL->buf = (char *) fs_get((LOCAL->buflen = max (*size,(long) CHUNK))+1);
  601.   }
  602.                 /* copy the text */
  603.   if (m->headersize) memcpy (LOCAL->buf,m->header,m->headersize);
  604.   if (m->bodysize) memcpy (LOCAL->buf + m->headersize,m->body,m->bodysize);
  605.   LOCAL->buf[*size] = '\0';    /* tie off string */
  606.   return LOCAL->buf;
  607. }
  608.  
  609. /* Berkeley mail fetch message header
  610.  * Accepts: MAIL stream
  611.  *        message # to fetch
  612.  * Returns: message header in RFC822 format
  613.  */
  614.  
  615. char *bezerk_fetchheader (MAILSTREAM *stream,long msgno)
  616. {
  617.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  618.                 /* copy the string */
  619.   return strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,m->header,m->headersize);
  620. }
  621.  
  622.  
  623. /* Berkeley mail fetch message text (body only)
  624.  * Accepts: MAIL stream
  625.  *        message # to fetch
  626.  * Returns: message text in RFC822 format
  627.  */
  628.  
  629. char *bezerk_fetchtext (MAILSTREAM *stream,long msgno)
  630. {
  631.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  632.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  633.   if (!elt->seen) {        /* if message not seen */
  634.     elt->seen = T;        /* mark message as seen */
  635.                 /* recalculate Status/X-Status lines */
  636.     bezerk_update_status (m->status,elt);
  637.     LOCAL->dirty = T;        /* note stream is now dirty */
  638.   }
  639.   return strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,m->body,m->bodysize);
  640. }
  641.  
  642. /* Berkeley fetch message body as a structure
  643.  * Accepts: Mail stream
  644.  *        message # to fetch
  645.  *        section specifier
  646.  *        pointer to length
  647.  * Returns: pointer to section of message body
  648.  */
  649.  
  650. char *bezerk_fetchbody (MAILSTREAM *stream,long m,char *s,unsigned long *len)
  651. {
  652.   BODY *b;
  653.   PART *pt;
  654.   unsigned long i;
  655.   char *base = LOCAL->msgs[m - 1]->body;
  656.   unsigned long offset = 0;
  657.   MESSAGECACHE *elt = mail_elt (stream,m);
  658.                 /* make sure have a body */
  659.   if (!(bezerk_fetchstructure (stream,m,&b) && b && s && *s &&
  660.     ((i = strtol (s,&s,10)) > 0))) return NIL;
  661.   do {                /* until find desired body part */
  662.                 /* multipart content? */
  663.     if (b->type == TYPEMULTIPART) {
  664.       pt = b->contents.part;    /* yes, find desired part */
  665.       while (--i && (pt = pt->next));
  666.       if (!pt) return NIL;    /* bad specifier */
  667.                 /* note new body, check valid nesting */
  668.       if (((b = &pt->body)->type == TYPEMULTIPART) && !*s) return NIL;
  669.       offset = pt->offset;    /* get new offset */
  670.     }
  671.     else if (i != 1) return NIL;/* otherwise must be section 1 */
  672.                 /* need to go down further? */
  673.     if (i = *s) switch (b->type) {
  674.     case TYPEMESSAGE:        /* embedded message */
  675.       offset = b->contents.msg.offset;
  676.       b = b->contents.msg.body;    /* get its body, drop into multipart case */
  677.     case TYPEMULTIPART:        /* multipart, get next section */
  678.       if ((*s++ == '.') && (i = strtol (s,&s,10)) > 0) break;
  679.     default:            /* bogus subpart specification */
  680.       return NIL;
  681.     }
  682.   } while (i);
  683.                 /* lose if body bogus */
  684.   if ((!b) || b->type == TYPEMULTIPART) return NIL;
  685.   if (!elt->seen) {        /* if message not seen */
  686.     elt->seen = T;        /* mark message as seen */
  687.                 /* recalculate Status/X-Status lines */
  688.     bezerk_update_status (LOCAL->msgs[m - 1]->status,elt);
  689.     LOCAL->dirty = T;        /* note stream is now dirty */
  690.   }
  691.   return rfc822_contents (&LOCAL->buf,&LOCAL->buflen,len,base + offset,
  692.               b->size.ibytes,b->encoding);
  693. }
  694.  
  695. /* Berkeley mail set flag
  696.  * Accepts: MAIL stream
  697.  *        sequence
  698.  *        flag(s)
  699.  */
  700.  
  701. void bezerk_setflag (MAILSTREAM *stream,char *sequence,char *flag)
  702. {
  703.   MESSAGECACHE *elt;
  704.   long i;
  705.   short f = bezerk_getflags (stream,flag);
  706.   if (!f) return;        /* no-op if no flags to modify */
  707.                 /* get sequence and loop on it */
  708.   if (mail_sequence (stream,sequence)) for (i = 1; i <= stream->nmsgs; i++)
  709.     if ((elt = mail_elt (stream,i))->sequence) {
  710.                 /* set all requested flags */
  711.       if (f&fSEEN) elt->seen = T;
  712.       if (f&fDELETED) elt->deleted = T;
  713.       if (f&fFLAGGED) elt->flagged = T;
  714.       if (f&fANSWERED) elt->answered = T;
  715.                 /* recalculate Status/X-Status lines */
  716.       bezerk_update_status (LOCAL->msgs[i - 1]->status,elt);
  717.       LOCAL->dirty = T;        /* note stream is now dirty */
  718.     }
  719. }
  720.  
  721.  
  722. /* Berkeley mail clear flag
  723.  * Accepts: MAIL stream
  724.  *        sequence
  725.  *        flag(s)
  726.  */
  727.  
  728. void bezerk_clearflag (MAILSTREAM *stream,char *sequence,char *flag)
  729. {
  730.   MESSAGECACHE *elt;
  731.   long i;
  732.   short f = bezerk_getflags (stream,flag);
  733.   if (!f) return;        /* no-op if no flags to modify */
  734.                 /* get sequence and loop on it */
  735.   if (mail_sequence (stream,sequence)) for (i = 1; i <= stream->nmsgs; i++)
  736.     if ((elt = mail_elt (stream,i))->sequence) {
  737.                 /* clear all requested flags */
  738.       if (f&fSEEN) elt->seen = NIL;
  739.       if (f&fDELETED) elt->deleted = NIL;
  740.       if (f&fFLAGGED) elt->flagged = NIL;
  741.       if (f&fANSWERED) elt->answered = NIL;
  742.                 /* recalculate Status/X-Status lines */
  743.       bezerk_update_status (LOCAL->msgs[i - 1]->status,elt);
  744.       LOCAL->dirty = T;        /* note stream is now dirty */
  745.     }
  746. }
  747.  
  748. /* Berkeley mail search for messages
  749.  * Accepts: MAIL stream
  750.  *        search criteria
  751.  */
  752.  
  753. void bezerk_search (MAILSTREAM *stream,char *criteria)
  754. {
  755.   long i,n;
  756.   char *d;
  757.   search_t f;
  758.                 /* initially all searched */
  759.   for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->searched = T;
  760.                 /* get first criterion */
  761.   if (criteria && (criteria = strtok (criteria," "))) {
  762.                 /* for each criterion */
  763.     for (; criteria; (criteria = strtok (NIL," "))) {
  764.       f = NIL; d = NIL; n = 0;    /* init then scan the criterion */
  765.       switch (*ucase (criteria)) {
  766.       case 'A':            /* possible ALL, ANSWERED */
  767.     if (!strcmp (criteria+1,"LL")) f = bezerk_search_all;
  768.     else if (!strcmp (criteria+1,"NSWERED")) f = bezerk_search_answered;
  769.     break;
  770.       case 'B':            /* possible BCC, BEFORE, BODY */
  771.     if (!strcmp (criteria+1,"CC"))
  772.       f = bezerk_search_string (bezerk_search_bcc,&d,&n);
  773.     else if (!strcmp (criteria+1,"EFORE"))
  774.       f = bezerk_search_date (bezerk_search_before,&n);
  775.     else if (!strcmp (criteria+1,"ODY"))
  776.       f = bezerk_search_string (bezerk_search_body,&d,&n);
  777.     break;
  778.       case 'C':            /* possible CC */
  779.     if (!strcmp (criteria+1,"C")) 
  780.       f = bezerk_search_string (bezerk_search_cc,&d,&n);
  781.     break;
  782.       case 'D':            /* possible DELETED */
  783.     if (!strcmp (criteria+1,"ELETED")) f = bezerk_search_deleted;
  784.     break;
  785.       case 'F':            /* possible FLAGGED, FROM */
  786.     if (!strcmp (criteria+1,"LAGGED")) f = bezerk_search_flagged;
  787.     else if (!strcmp (criteria+1,"ROM"))
  788.       f = bezerk_search_string (bezerk_search_from,&d,&n);
  789.     break;
  790.       case 'K':            /* possible KEYWORD */
  791.     if (!strcmp (criteria+1,"EYWORD"))
  792.       f = bezerk_search_flag (bezerk_search_keyword,&d);
  793.     break;
  794.       case 'N':            /* possible NEW */
  795.     if (!strcmp (criteria+1,"EW")) f = bezerk_search_new;
  796.     break;
  797.  
  798.       case 'O':            /* possible OLD, ON */
  799.     if (!strcmp (criteria+1,"LD")) f = bezerk_search_old;
  800.     else if (!strcmp (criteria+1,"N"))
  801.       f = bezerk_search_date (bezerk_search_on,&n);
  802.     break;
  803.       case 'R':            /* possible RECENT */
  804.     if (!strcmp (criteria+1,"ECENT")) f = bezerk_search_recent;
  805.     break;
  806.       case 'S':            /* possible SEEN, SINCE, SUBJECT */
  807.     if (!strcmp (criteria+1,"EEN")) f = bezerk_search_seen;
  808.     else if (!strcmp (criteria+1,"INCE"))
  809.       f = bezerk_search_date (bezerk_search_since,&n);
  810.     else if (!strcmp (criteria+1,"UBJECT"))
  811.       f = bezerk_search_string (bezerk_search_subject,&d,&n);
  812.     break;
  813.       case 'T':            /* possible TEXT, TO */
  814.     if (!strcmp (criteria+1,"EXT"))
  815.       f = bezerk_search_string (bezerk_search_text,&d,&n);
  816.     else if (!strcmp (criteria+1,"O"))
  817.       f = bezerk_search_string (bezerk_search_to,&d,&n);
  818.     break;
  819.       case 'U':            /* possible UN* */
  820.     if (criteria[1] == 'N') {
  821.       if (!strcmp (criteria+2,"ANSWERED")) f = bezerk_search_unanswered;
  822.       else if (!strcmp (criteria+2,"DELETED")) f = bezerk_search_undeleted;
  823.       else if (!strcmp (criteria+2,"FLAGGED")) f = bezerk_search_unflagged;
  824.       else if (!strcmp (criteria+2,"KEYWORD"))
  825.         f = bezerk_search_flag (bezerk_search_unkeyword,&d);
  826.       else if (!strcmp (criteria+2,"SEEN")) f = bezerk_search_unseen;
  827.     }
  828.     break;
  829.       default:            /* we will barf below */
  830.     break;
  831.       }
  832.       if (!f) {            /* if can't determine any criteria */
  833.     sprintf (LOCAL->buf,"Unknown search criterion: %.30s",criteria);
  834.     mm_log (LOCAL->buf,ERROR);
  835.     return;
  836.       }
  837.                 /* run the search criterion */
  838.       for (i = 1; i <= stream->nmsgs; ++i)
  839.     if (mail_elt (stream,i)->searched && !(*f) (stream,i,d,n))
  840.       mail_elt (stream,i)->searched = NIL;
  841.     }
  842.                 /* report search results to main program */
  843.     for (i = 1; i <= stream->nmsgs; ++i)
  844.       if (mail_elt (stream,i)->searched) mail_searched (stream,i);
  845.   }
  846. }
  847.  
  848. /* Berkeley mail ping mailbox
  849.  * Accepts: MAIL stream
  850.  * Returns: T if stream alive, else NIL
  851.  * No-op for readonly files, since read/writer can expunge it from under us!
  852.  */
  853.  
  854. long bezerk_ping (MAILSTREAM *stream)
  855. {
  856.   char lock[MAILTMPLEN];
  857.   struct stat sbuf;
  858.   int fd;
  859.                 /* does he want to give up readwrite? */
  860.   if (stream->readonly && LOCAL->ld) {
  861.     flock (LOCAL->ld,LOCK_UN);    /* yes, release the lock */
  862.     close (LOCAL->ld);        /* close the lock file */
  863.     LOCAL->ld = NIL;        /* no more lock fd */
  864.     unlink (LOCAL->lname);    /* delete it */
  865.     fs_give ((void **) &LOCAL->lname);
  866.   }
  867.                 /* make sure it is alright to do this at all */
  868.   if (LOCAL && LOCAL->ld && !stream->lock) {
  869.                 /* get current mailbox size */
  870.     stat (LOCAL->name,&sbuf);    /* parse if mailbox changed */
  871.     if ((sbuf.st_size != LOCAL->filesize) &&
  872.     ((fd = bezerk_parse (stream,lock,LOCK_SH)) >= 0)) {
  873.                 /* unlock mailbox */
  874.       bezerk_unlock (fd,stream,lock);
  875.       mail_unlock (stream);    /* and stream */
  876.     }
  877.   }
  878.   return LOCAL ? T : NIL;    /* return if still alive */
  879. }
  880.  
  881. /* Berkeley mail check mailbox
  882.  * Accepts: MAIL stream
  883.  * No-op for readonly files, since read/writer can expunge it from under us!
  884.  */
  885.  
  886. void bezerk_check (MAILSTREAM *stream)
  887. {
  888.   char lock[MAILTMPLEN];
  889.   int fd;
  890.                 /* parse and lock mailbox */
  891.   if (LOCAL && LOCAL->ld && ((fd = bezerk_parse (stream,lock,LOCK_EX)) >= 0)) {
  892.     if (LOCAL->dirty && bezerk_extend (stream,fd,"Unable to update mailbox"))
  893.       bezerk_save (stream,fd);    /* dump checkpoint if needed */
  894.                 /* flush locks */
  895.     bezerk_unlock (fd,stream,lock);
  896.     mail_unlock (stream);
  897.   }
  898.   if (LOCAL && LOCAL->ld) mm_log ("Check completed",NIL);
  899. }
  900.  
  901. /* Berkeley mail expunge mailbox
  902.  * Accepts: MAIL stream
  903.  */
  904.  
  905. void bezerk_expunge (MAILSTREAM *stream)
  906. {
  907.   int fd,j;
  908.   long i = 1;
  909.   long n = 0;
  910.   unsigned long recent;
  911.   MESSAGECACHE *elt;
  912.   char *r = "No messages deleted, so no update needed";
  913.   char lock[MAILTMPLEN];
  914.   if (LOCAL && LOCAL->ld) {    /* parse and lock mailbox */
  915.     if ((fd = bezerk_parse (stream,lock,LOCK_EX)) >= 0) {
  916.       recent = stream->recent;    /* get recent now that new ones parsed */
  917.       while ((j = (i<=stream->nmsgs)) && !(elt = mail_elt (stream,i))->deleted)
  918.     i++;            /* find first deleted message */
  919.       if (j) {            /* found one? */
  920.                 /* make sure we can do the worst case thing */
  921.     if (bezerk_extend (stream,fd,"Unable to expunge mailbox")) {
  922.       do {            /* flush deleted messages */
  923.         if ((elt = mail_elt (stream,i))->deleted) {
  924.                 /* if recent, note one less recent message */
  925.           if (elt->recent) --recent;
  926.                 /* flush local cache entry */
  927.           fs_give ((void **) &LOCAL->msgs[i - 1]);
  928.           for (j = i; j < stream->nmsgs; j++)
  929.         LOCAL->msgs[j - 1] = LOCAL->msgs[j];
  930.           LOCAL->msgs[stream->nmsgs - 1] = NIL;
  931.                 /* notify upper levels */
  932.           mail_expunged (stream,i);
  933.           n++;        /* count another expunged message */
  934.         }
  935.         else i++;        /* otherwise try next message */
  936.       } while (i <= stream->nmsgs);
  937.                 /* dump checkpoint of the results */
  938.       bezerk_save (stream,fd);
  939.       sprintf ((r = LOCAL->buf),"Expunged %d messages",n);
  940.     }
  941.       }
  942.                 /* notify upper level, free locks */
  943.       mail_exists (stream,stream->nmsgs);
  944.       mail_recent (stream,recent);
  945.       bezerk_unlock (fd,stream,lock);
  946.       mail_unlock (stream);
  947.     }
  948.   }
  949.   else r = "Expunge ignored on readonly mailbox";
  950.   if (LOCAL && !stream->silent) mm_log (r,NIL);
  951. }
  952.  
  953. /* Berkeley mail copy message(s)
  954.  * Accepts: MAIL stream
  955.  *        sequence
  956.  *        destination mailbox
  957.  * Returns: T if copy successful, else NIL
  958.  */
  959.  
  960. long bezerk_copy (MAILSTREAM *stream,char *sequence,char *mailbox)
  961. {
  962.                 /* copy the messages */
  963.   return (mail_sequence (stream,sequence)) ?
  964.     bezerk_copy_messages (stream,mailbox) : NIL;
  965. }
  966.  
  967.  
  968. /* Berkeley mail move message(s)
  969.  * Accepts: MAIL stream
  970.  *        sequence
  971.  *        destination mailbox
  972.  * Returns: T if move successful, else NIL
  973.  */
  974.  
  975. long bezerk_move (MAILSTREAM *stream,char *sequence,char *mailbox)
  976. {
  977.   long i;
  978.   MESSAGECACHE *elt;
  979.   if (!(mail_sequence (stream,sequence) &&
  980.     bezerk_copy_messages (stream,mailbox))) return NIL;
  981.                 /* delete all requested messages */
  982.   for (i = 1; i <= stream->nmsgs; i++)
  983.     if ((elt = mail_elt (stream,i))->sequence) {
  984.       elt->deleted = T;        /* mark message deleted */
  985.                 /* recalculate Status/X-Status lines */
  986.       bezerk_update_status (LOCAL->msgs[i - 1]->status,elt);
  987.       LOCAL->dirty = T;        /* note stream is now dirty */
  988.     }
  989.   return T;
  990. }
  991.  
  992. /* Berkeley mail append message from stringstruct
  993.  * Accepts: MAIL stream
  994.  *        destination mailbox
  995.  *        stringstruct of messages to append
  996.  * Returns: T if append successful, else NIL
  997.  */
  998.  
  999. long bezerk_append (MAILSTREAM *stream,char *mailbox,STRING *message)
  1000. {
  1001.   struct stat sbuf;
  1002.   int fd;
  1003.   char c,tmp[MAILTMPLEN],lock[MAILTMPLEN];
  1004.   int i = 0;
  1005.   char *s = tmp;
  1006.   long t = time (0);
  1007.   long size = SIZE (message);
  1008.   if ((fd = bezerk_lock (bezerk_file (tmp,mailbox),O_WRONLY|O_APPEND|O_CREAT,
  1009.              S_IREAD|S_IWRITE,lock,LOCK_EX)) < 0) {
  1010.     sprintf (tmp,"Can't open append mailbox: %s",strerror (errno));
  1011.     mm_log (tmp,ERROR);
  1012.     return NIL;
  1013.   }
  1014.   mm_critical (stream);        /* go critical */
  1015.   fstat (fd,&sbuf);        /* get current file size */
  1016.   sprintf (tmp,"From %s@%s %s",myusername (),lhostn,ctime (&t));
  1017.                 /* write header */
  1018.   if (write (fd,tmp,strlen (tmp)) < 0) {
  1019.     sprintf (tmp,"Header write failed: %s",strerror (errno));
  1020.     mm_log (tmp,ERROR);
  1021.     ftruncate (fd,sbuf.st_size);
  1022.   }  
  1023.   else while (size--) {        /* copy text, tossing out CR's */
  1024.     if ((c = SNX (message)) != '\015') s[i++] = c;
  1025.                 /* dump if full buffer, no more data, or NL */
  1026.     if ((!size) || (i == MAILTMPLEN) || (c == '\n')) {
  1027.                 /* prepend broken to leading "From " */
  1028.       if ((i > 4) && (tmp[0] == 'F') && (tmp[1] == 'r') && (tmp[2] == 'o') &&
  1029.       (tmp[3] == 'm') && (tmp[4] == ' ')) write (fd,">",1);
  1030.       if ((write (fd,tmp,i)) < 0) {
  1031.     sprintf (tmp,"Message append failed: %s",strerror (errno));
  1032.     mm_log (tmp,ERROR);
  1033.     ftruncate (fd,sbuf.st_size);
  1034.     break;
  1035.       }
  1036.       i = 0;            /* restart buffer */
  1037.                 /* write out final newline if at end */
  1038.       if (!size) write (fd,"\n",1);
  1039.     }
  1040.   }
  1041.   fsync (fd);            /* force out the update */
  1042.   bezerk_unlock (fd,NIL,lock);    /* unlock and close mailbox */
  1043.   mm_nocritical (stream);    /* release critical */
  1044.   return T;            /* return success */
  1045. }
  1046.  
  1047. /* Berkeley garbage collect stream
  1048.  * Accepts: Mail stream
  1049.  *        garbage collection flags
  1050.  */
  1051.  
  1052. void bezerk_gc (MAILSTREAM *stream,long gcflags)
  1053. {
  1054.   /* nothing here for now */
  1055. }
  1056.  
  1057. /* Internal routines */
  1058.  
  1059.  
  1060. /* Berkeley mail abort stream
  1061.  * Accepts: MAIL stream
  1062.  */
  1063.  
  1064. void bezerk_abort (MAILSTREAM *stream)
  1065. {
  1066.   long i;
  1067.   if (LOCAL) {            /* only if a file is open */
  1068.     if (LOCAL->name) fs_give ((void **) &LOCAL->name);
  1069.     if (LOCAL->ld) {        /* have a mailbox lock? */
  1070.       flock (LOCAL->ld,LOCK_UN);/* yes, release the lock */
  1071.       close (LOCAL->ld);    /* close the lock file */
  1072.       unlink (LOCAL->lname);    /* and delete it */
  1073.     }
  1074.     fs_give ((void **) &LOCAL->lname);
  1075.     if (LOCAL->msgs) {        /* free local cache */
  1076.       for (i = 0; i < stream->nmsgs; ++i) fs_give ((void **) &LOCAL->msgs[i]);
  1077.       fs_give ((void **) &LOCAL->msgs);
  1078.     }
  1079.                 /* free local text buffers */
  1080.     if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
  1081.                 /* nuke the local data */
  1082.     fs_give ((void **) &stream->local);
  1083.     stream->dtb = NIL;        /* log out the DTB */
  1084.   }
  1085. }
  1086.  
  1087. /* Berkeley mail generate file string
  1088.  * Accepts: temporary buffer to write into
  1089.  *        mailbox name string
  1090.  * Returns: local file string
  1091.  */
  1092.  
  1093.  
  1094. char *bezerk_file (char *dst,char *name)
  1095. {
  1096.   struct passwd *pw;
  1097.   char *s,*t,tmp[MAILTMPLEN];
  1098.   switch (*name) {
  1099.   case '*':            /* bboard? */
  1100.     sprintf (tmp,"~ftp/%s",(name[1] == '/') ? name+2 : name+1);
  1101.     dst = bezerk_file (dst,tmp);/* recurse to get result */
  1102.     break;
  1103.   case '/':            /* absolute file path */
  1104.     strcpy (dst,name);        /* copy the mailbox name */
  1105.     break;
  1106.   case '~':            /* home directory */
  1107.     if (name[1] == '/') t = myhomedir ();
  1108.     else {
  1109.       strcpy (tmp,name + 1);    /* copy user name */
  1110.       if (s = strchr (tmp,'/')) *s = '\0';
  1111.       t = ((pw = getpwnam (tmp)) && pw->pw_dir) ? pw->pw_dir : "/NOSUCHUSER";
  1112.     }
  1113.     sprintf (dst,"%s%s",t,(s = strchr (name,'/')) ? s : "");
  1114.     break;
  1115.   default:            /* other name */
  1116.     if (strcmp (ucase (strcpy (dst,name)),"INBOX"))
  1117.       sprintf (dst,"%s/%s",myhomedir (),name);
  1118.                 /* INBOX becomes mail spool directory file */
  1119.     else sprintf (dst,MAILFILE,myusername ());
  1120.   }
  1121.   return dst;
  1122. }
  1123.  
  1124. /* Berkeley open and lock mailbox
  1125.  * Accepts: file name to open/lock
  1126.  *        file open mode
  1127.  *        destination buffer for lock file name
  1128.  *        type of locking operation (LOCK_SH or LOCK_EX)
  1129.  */
  1130.  
  1131. int bezerk_lock (char *file,int flags,int mode,char *lock,int op)
  1132. {
  1133.   int fd,ld,j;
  1134.   int i = LOCKTIMEOUT * 60 - 1;
  1135.   char tmp[MAILTMPLEN];
  1136.   struct timeval tp;
  1137.   struct stat sb;
  1138.                 /* build lock filename */
  1139.   strcat (bezerk_file (lock,file),".lock");
  1140.   do {                /* until OK or out of tries */
  1141.     gettimeofday (&tp,NIL);    /* get the time now */
  1142. #ifdef NFSKLUDGE
  1143.   /* SUN-OS had an NFS, As kludgy as an albatross;
  1144.    * And everywhere that it was installed, It was a total loss.  -- MRC 9/25/91
  1145.    */
  1146.                 /* build hitching post file name */
  1147.     sprintf (tmp,"%s.%d.%d.",lock,time (0),getpid ());
  1148.     j = strlen (tmp);        /* append local host name */
  1149.     gethostname (tmp + j,(MAILTMPLEN - j) - 1);
  1150.                 /* try to get hitching-post file */
  1151.     if ((ld = open (tmp,O_WRONLY|O_CREAT|O_EXCL,0666)) < 0) {
  1152.                 /* prot fail & non-ex, don't use lock files */
  1153.       if ((errno == EACCES) && (stat (tmp,&sb))) *lock = '\0';
  1154.       else {            /* otherwise something strange is going on */
  1155.     sprintf (tmp,"Error creating %s: %s",lock,strerror (errno));
  1156.     mm_log (tmp,WARN);    /* this is probably not good */
  1157.                 /* don't use lock files if not one of these */
  1158.     if ((errno != EEXIST) && (errno != EACCES)) *lock = '\0';
  1159.       }
  1160.     }
  1161.     else {            /* got a hitching-post */
  1162.       chmod (tmp,0666);        /* make sure others can break the lock */
  1163.       close (ld);        /* close the hitching-post */
  1164.       link (tmp,lock);        /* tie hitching-post to lock, ignore failure */
  1165.       stat (tmp,&sb);        /* get its data */
  1166.       unlink (tmp);        /* flush hitching post */
  1167.       /* If link count .ne. 2, hitch failed.  Set ld to -1 as if open() failed
  1168.      so we try again.  If extant lock file and time now is .gt. file time
  1169.      plus timeout interval, flush the lock so can win next time around. */
  1170.       if ((ld = (sb.st_nlink != 2) ? -1 : 0) && (!stat (lock,&sb)) &&
  1171.       (tp.tv_sec > sb.st_ctime + LOCKTIMEOUT * 60)) unlink (lock);
  1172.     }
  1173.  
  1174. #else
  1175.   /* This works on modern Unix systems which are not afflicted with NFS mail.
  1176.    * "Modern" means that O_EXCL works.  I think that NFS mail is a terrible
  1177.    * idea -- that's what IMAP is for -- but some people insist upon losing...
  1178.    */
  1179.                 /* try to get the lock */
  1180.     if ((ld = open (lock,O_WRONLY|O_CREAT|O_EXCL,0666)) < 0) switch (errno) {
  1181.     case EEXIST:        /* if extant and old, grab it for ourselves */
  1182.       if ((!stat (lock,&sb)) && tp.tv_sec > sb.st_ctime + LOCKTIMEOUT * 60)
  1183.     ld = open (lock,O_WRONLY|O_CREAT,0666);
  1184.       break;
  1185.     case EACCES:        /* protection fail, ignore if non-ex or old */
  1186.       if (stat (lock,&sb) || (tp.tv_sec > sb.st_ctime + LOCKTIMEOUT * 60))
  1187.     *lock = '\0';        /* assume no world write mail spool dir */
  1188.       break;
  1189.     default:            /* some other failure */
  1190.       sprintf (tmp,"Error creating %s: %s",lock,strerror (errno));
  1191.       mm_log (tmp,WARN);    /* this is probably not good */
  1192.       *lock = '\0';        /* don't use lock files */
  1193.       break;
  1194.     }
  1195.     if (ld >= 0) {        /* if made a lock file */
  1196.       chmod (tmp,0666);        /* make sure others can break the lock */
  1197.       close (ld);        /* close the lock file */
  1198.     }
  1199. #endif
  1200.     if ((ld < 0) && *lock) {    /* if failed to make lock file and retry OK */
  1201.       if (!(i%15)) {
  1202.     sprintf (tmp,"Mailbox %s is locked, will override in %d seconds...",
  1203.          file,i);
  1204.     mm_log (tmp,WARN);
  1205.       }
  1206.       sleep (1);        /* wait 1 second before next try */
  1207.     }
  1208.   } while (i-- && ld < 0 && *lock);
  1209.                 /* open file */
  1210.   if ((fd = open (file,flags,mode)) >= 0) flock (fd,op);
  1211.   else {            /* open failed */
  1212.     j = errno;            /* preserve error code */
  1213.     if (*lock) unlink (lock);    /* flush the lock file if any */
  1214.     errno = j;            /* restore error code */
  1215.   }
  1216.   return fd;
  1217. }
  1218.  
  1219. /* Berkeley unlock and close mailbox
  1220.  * Accepts: file descriptor
  1221.  *        (optional) mailbox stream to check atime/mtime
  1222.  *        (optional) lock file name
  1223.  */
  1224.  
  1225. void bezerk_unlock (int fd,MAILSTREAM *stream,char *lock)
  1226. {
  1227.   struct stat sbuf;
  1228.   struct timeval tp[2];
  1229.   fstat (fd,&sbuf);        /* get file times */
  1230.                 /* if stream and csh would think new mail */
  1231.   if (stream && (sbuf.st_atime <= sbuf.st_mtime)) {
  1232.     gettimeofday (&tp[0],NIL);    /* set atime to now */
  1233.                 /* set mtime to (now - 1) if necessary */
  1234.     tp[1].tv_sec = tp[0].tv_sec > sbuf.st_mtime ? sbuf.st_mtime :
  1235.       tp[0].tv_sec - 1;
  1236.     tp[1].tv_usec = 0;        /* oh well */
  1237.                 /* set the times, note change */
  1238.     if (!utimes (LOCAL->name,tp)) LOCAL->filetime = tp[1].tv_sec;
  1239.   }
  1240.   flock (fd,LOCK_UN);        /* release flock'ers */
  1241.   close (fd);            /* close the file */
  1242.                 /* flush the lock file if any */
  1243.   if (lock && *lock) unlink (lock);
  1244. }
  1245.  
  1246. /* Berkeley mail parse and lock mailbox
  1247.  * Accepts: MAIL stream
  1248.  *        space to write lock file name
  1249.  *        type of locking operation
  1250.  * Returns: file descriptor if parse OK, mailbox is locked shared
  1251.  *        -1 if failure, stream aborted
  1252.  */
  1253.  
  1254. int bezerk_parse (MAILSTREAM *stream,char *lock,int op)
  1255. {
  1256.   int fd;
  1257.   long delta,i,j,is,is1;
  1258.   char *s,*s1,*t = NIL,*e;
  1259.   int ti = 0,zn = 0;
  1260.   int first = T;
  1261.   long nmsgs = stream->nmsgs;
  1262.   long recent = stream->recent;
  1263.   struct stat sbuf;
  1264.   MESSAGECACHE *elt;
  1265.   FILECACHE *m = NIL,*n = NIL;
  1266.   mail_lock (stream);        /* guard against recursion or pingers */
  1267.                 /* open and lock mailbox (shared OK) */
  1268.   if ((fd = bezerk_lock (LOCAL->name,LOCAL->ld ? O_RDWR : O_RDONLY,NIL,
  1269.              lock,op)) < 0) {
  1270.                 /* failed, OK for non-ex file? */
  1271.     if ((errno != ENOENT) || LOCAL->filesize) {
  1272.       sprintf (LOCAL->buf,"Mailbox open failed, aborted: %s",strerror (errno));
  1273.       mm_log (LOCAL->buf,ERROR);
  1274.       bezerk_abort (stream);
  1275.     }
  1276.     else {            /* this is to allow for non-ex INBOX */
  1277.       mail_exists (stream,0);    /* make sure upper level sees this as empty */
  1278.       mail_recent (stream,0);
  1279.     }
  1280.     mail_unlock (stream);
  1281.     return -1;
  1282.   }
  1283.   fstat (fd,&sbuf);        /* get status */
  1284.                 /* calculate change in size */
  1285.   if ((delta = sbuf.st_size - LOCAL->filesize) < 0) {
  1286.     sprintf (LOCAL->buf,"Mailbox shrank from %d to %d bytes, aborted",
  1287.          LOCAL->filesize,sbuf.st_size);
  1288.     mm_log (LOCAL->buf,ERROR);    /* this is pretty bad */
  1289.     bezerk_unlock (fd,stream,lock);
  1290.     bezerk_abort (stream);
  1291.     mail_unlock (stream);
  1292.     return -1;
  1293.   }
  1294.  
  1295.   else if (delta) {        /* get to that position in the file */
  1296.     lseek (fd,LOCAL->filesize,L_SET);
  1297.     s = s1 = LOCAL->buf;    /* initial read-in location */
  1298.     i = 0;            /* initial unparsed read-in count */
  1299.     do {
  1300.       i = min (CHUNK,delta);    /* calculate read-in size */
  1301.                 /* increase the read-in buffer if necessary */
  1302.       if ((j = i + (s1 - s)) >= LOCAL->buflen) {
  1303.     is = s - LOCAL->buf;    /* note former start of message position */
  1304.     is1 = s1 - LOCAL->buf;    /* and start of new data position */
  1305.     if (s1 - s) fs_resize ((void **) &LOCAL->buf,(LOCAL->buflen = j) + 1);
  1306.     else {            /* fs_resize would do an unnecessary copy */
  1307.       fs_give ((void **) &LOCAL->buf);
  1308.       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = j) + 1);
  1309.     }
  1310.     s = LOCAL->buf + is;    /* new start of message */
  1311.     s1 = LOCAL->buf + is1;    /* new start of new data */
  1312.       }
  1313.       s1[i] = '\0';        /* tie off chunk */
  1314.       if (read (fd,s1,i) < 0) {    /* read a chunk of new text */
  1315.     sprintf (LOCAL->buf,"Error reading mail file: %s",strerror (errno));
  1316.     mm_log (LOCAL->buf,ERROR);
  1317.     bezerk_unlock (fd,stream,lock);
  1318.     bezerk_abort (stream);
  1319.     mail_unlock (stream);
  1320.     return -1;
  1321.       }
  1322.       delta -= i;        /* account for data read in */
  1323.                 /* validate newly-appended data */
  1324.       if (first) {        /* only do this first time! */
  1325.     if (!((*s =='F') && VALID (s,t,ti,zn))) {
  1326.       mm_log ("Mailbox format invalidated (consult an expert), aborted",
  1327.           ERROR);
  1328.       bezerk_unlock (fd,stream,lock);
  1329.       bezerk_abort (stream);
  1330.       mail_unlock (stream);
  1331.       return -1;
  1332.     }
  1333.     first = NIL;        /* don't do this again */
  1334.       }
  1335.  
  1336.                 /* found end of message or end of data? */
  1337.       while ((e = bezerk_eom (s,s1,i)) || !delta) {
  1338.     nmsgs++;        /* yes, have a new message */
  1339.     if (e) j = (e - s) - 1;    /* calculate message length */
  1340.     else j = strlen (s) - 1;/* otherwise is remainder of data */
  1341.     if (m) {        /* new cache needed, have previous data? */
  1342.       n->header = (char *) fs_get (sizeof (FILECACHE) + j + 1);
  1343.       n = (FILECACHE *) n->header;
  1344.     }
  1345.     else m = n = (FILECACHE *) fs_get (sizeof (FILECACHE) + j + 1);
  1346.                 /* copy message data */
  1347.     strncpy (n->internal,s,j);
  1348.     n->internal[j] = '\0';
  1349.     n->header = NIL;    /* initially no link */
  1350.     n->headersize = j;    /* stash away buffer length */
  1351.     if (e) {        /* saw end of message? */
  1352.       i -= e - s1;        /* new unparsed data count */
  1353.       s = s1 = e;        /* advance to new message */
  1354.     }
  1355.     else break;        /* else punt this loop */
  1356.       }
  1357.       if (delta) {        /* end of message not found? */
  1358.     s1 += i;        /* end of unparsed data */
  1359.     if (s != LOCAL->buf){    /* message doesn't begin at buffer? */
  1360.       i = s1 - s;        /* length of message so far */
  1361.       memmove (LOCAL->buf,s,i);
  1362.       s = LOCAL->buf;    /* message now starts at buffer origin */
  1363.       s1 = s + i;        /* calculate new end of unparsed data */
  1364.     }
  1365.       }
  1366.     } while (delta);        /* until nothing more new to read */
  1367.   }
  1368.   else {            /* no change, don't babble if never got time */
  1369.     if (LOCAL->filetime && LOCAL->filetime != sbuf.st_mtime)
  1370.       mm_log ("New mailbox modification time but apparently no changes",WARN);
  1371.   }
  1372.                 /* expand the primary cache */
  1373.   (*mailcache) (stream,nmsgs,CH_SIZE);
  1374.   if (LOCAL->msgs) {        /* have a cache yet? */
  1375.     if (nmsgs >= LOCAL->cachesize)
  1376.       fs_resize ((void **) &LOCAL->msgs,
  1377.          (LOCAL->cachesize += CACHEINCREMENT) * sizeof (FILECACHE *));
  1378.   }
  1379.   else LOCAL->msgs = (FILECACHE **)
  1380.     fs_get ((LOCAL->cachesize = nmsgs + CACHEINCREMENT) *sizeof (FILECACHE *));
  1381.  
  1382.   if (LOCAL->buflen > CHUNK) {    /* maybe move where the buffer is in memory*/
  1383.     fs_give ((void **) &LOCAL->buf);
  1384.     LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNK) + 1);
  1385.   }
  1386.   for (i = stream->nmsgs, n = m; i < nmsgs; i++) {
  1387.     LOCAL->msgs[i] = m = n;    /* set cache, and next cache pointer */
  1388.     n = (FILECACHE *) n->header;
  1389.     /* This is a bugtrap for bogons in the new message cache, which may happen
  1390.      * if memory is corrupted.  Note that in the case of a totally empty
  1391.      * message, a newline is appended and counts adjusted.
  1392.      */
  1393.     if (!((s = m->internal) && VALID (s,t,ti,zn)))
  1394.       if (!(s && !strchr (s,'\n') && strcat (s,"\n") && VALID (s,t,ti,zn) &&
  1395.         m->headersize++))
  1396.     fatal ("Bogus entry in new cache list");
  1397.                 /* pointer to message header */
  1398.     m->header = s = strchr (t++,'\n') + 1;
  1399.     m->headersize -= m->header - m->internal;
  1400.     m->body = NIL;        /* assume no body as yet */
  1401.     m->bodysize = 0;
  1402.     recent++;            /* assume recent by default */
  1403.     (elt = mail_elt (stream,i+1))->recent = T;
  1404.                 /* calculate initial Status/X-Status lines */
  1405.     bezerk_update_status (m->status,elt);
  1406.                 /* generate plausable IMAPish date string */
  1407.     LOCAL->buf[2] = LOCAL->buf[6] = LOCAL->buf[20] = '-';
  1408.     LOCAL->buf[11] = ' ';
  1409.     LOCAL->buf[14] = LOCAL->buf[17] = ':';
  1410.                 /* dd */
  1411.     LOCAL->buf[0] = t[ti - 3]; LOCAL->buf[1] = t[ti - 2];
  1412.                 /* mmm */
  1413.     LOCAL->buf[3] = t[ti - 7]; LOCAL->buf[4] = t[ti - 6];
  1414.     LOCAL->buf[5] = t[ti - 5];
  1415.                 /* hh */
  1416.     LOCAL->buf[12] = t[ti]; LOCAL->buf[13] = t[ti + 1];
  1417.                 /* mm */
  1418.     LOCAL->buf[15] = t[ti + 3]; LOCAL->buf[16] = t[ti + 4];
  1419.     if (t[ti += 5] == ':') {    /* ss if present */
  1420.       LOCAL->buf[18] = t[++ti];
  1421.       LOCAL->buf[19] = t[++ti];
  1422.       ti++;            /* move to space */
  1423.     }
  1424.     else LOCAL->buf[18] = LOCAL->buf[19] = '0';
  1425.                 /* yy -- advance over timezone if necessary */
  1426.     if (zn == ++ti) ti += (((t[zn] == '+') || (t[zn] == '-')) ? 6 : 4);
  1427.     LOCAL->buf[7] = t[ti]; LOCAL->buf[8] = t[ti + 1];
  1428.     LOCAL->buf[9] = t[ti + 2]; LOCAL->buf[10] = t[ti + 3];
  1429.                 /* zzz */
  1430.     t = zn ? (t + zn) : "LCL";
  1431.     LOCAL->buf[21] = *t++; LOCAL->buf[22] = *t++; LOCAL->buf[23] = *t++;
  1432.     if ((LOCAL->buf[21] != '+') && (LOCAL->buf[21] != '-'))
  1433.       LOCAL->buf[24] = '\0';
  1434.     else {            /* numeric time zone */
  1435.       LOCAL->buf[24] = *t++; LOCAL->buf[25] = *t++;
  1436.       LOCAL->buf[26] = '\0'; LOCAL->buf[20] = ' ';
  1437.     }
  1438.                 /* set internal date */
  1439.     if (!mail_parse_date (elt,LOCAL->buf)) mm_log ("Unparsable date",WARN);
  1440.  
  1441.     is = 0;            /* initialize newline count */
  1442.     e = NIL;            /* no status stuff yet */
  1443.     do switch (*(t = s)) {    /* look at header lines */
  1444.     case 'X':            /* possible X-Status: line */
  1445.       if (s[1] == '-' && s[2] == 'S') s += 2;
  1446.       else {
  1447.     is++;            /* count another newline */
  1448.     break;            /* this is uninteresting after all */
  1449.       }
  1450.     case 'S':            /* possible Status: line */
  1451.       if (s[1] == 't' && s[2] == 'a' && s[3] == 't' && s[4] == 'u' &&
  1452.       s[5] == 's' && s[6] == ':') {
  1453.     if (!e) e = t;        /* note deletion point */
  1454.     s += 6;            /* advance to status flags */
  1455.     do switch (*s++) {    /* parse flags */
  1456.     case 'R':        /* message read */
  1457.       elt->seen = T;
  1458.       break;
  1459.     case 'O':        /* message old */
  1460.       if (elt->recent) {    /* don't do this more than once! */
  1461.         elt->recent = NIL;
  1462.         recent--;        /* not recent any longer... */
  1463.       }
  1464.       break;
  1465.     case 'D':        /* message deleted */
  1466.       elt->deleted = T;
  1467.       break;
  1468.     case 'F':        /* message flagged */
  1469.       elt ->flagged = T;
  1470.       break;
  1471.     case 'A':        /* message answered */
  1472.       elt ->answered = T;
  1473.       break;
  1474.     default:        /* some other crap */
  1475.       break;
  1476.     } while (*s && *s != '\n');
  1477.                 /* recalculate Status/X-Status lines */
  1478.     bezerk_update_status (m->status,elt);
  1479.       }
  1480.       else is++;        /* otherwise random line */
  1481.       break;
  1482.  
  1483.     case '\n':            /* end of header */
  1484.       m->body = ++s;        /* start of body is here */
  1485.       j = m->body - m->header;    /* new header size */
  1486.                 /* calculate body size */
  1487.       m->bodysize = m->headersize - j;
  1488.       if (e) {            /* saw status poop? */
  1489.     *e++ = '\n';        /* patch in trailing newline */
  1490.     m->headersize = e - m->header;
  1491.       }
  1492.       else m->headersize = j;    /* set header size */
  1493.       s = NIL;            /* don't scan any further */
  1494.       is++;            /* count a newline */
  1495.       break;
  1496.     case '\0':            /* end of message */
  1497.       if (e) {            /* saw status poop? */
  1498.     *e++ = '\n';        /* patch in trailing newline */
  1499.     m->headersize = e - m->header;
  1500.       }
  1501.       is++;            /* count an extra newline here */
  1502.       break;
  1503.     default:            /* anything else is uninteresting */
  1504.       if (e) {            /* have status stuff to worry about? */
  1505.     j = s - e;        /* yuck!!  calculate size of delete area */
  1506.                 /* blat remaining number of bytes down */
  1507.     memmove (e,s,m->header + m->headersize - s);
  1508.     m->headersize -= j;    /* update for new size */
  1509.     e = NIL;        /* no more delete area */
  1510.                 /* tie off old cruft */
  1511.     *(m->header + m->headersize) = '\0';
  1512.       }
  1513.       is++;
  1514.       break;
  1515.     } while (s && (s = strchr (s,'\n')) && s++);
  1516.                 /* count newlines in body */
  1517.     if (s = m->body) while (*s) if (*s++ == '\n') is++;
  1518.     elt->rfc822_size = m->headersize + m->bodysize + is;
  1519.   }
  1520.   if (n) fatal ("Cache link-list inconsistency");
  1521.   while (i < LOCAL->cachesize) LOCAL->msgs[i++] = NIL;
  1522.                 /* update parsed file size and time */
  1523.   LOCAL->filesize = sbuf.st_size;
  1524.   LOCAL->filetime = sbuf.st_mtime;
  1525.   mail_exists (stream,nmsgs);    /* notify upper level of new mailbox size */
  1526.   mail_recent (stream,recent);    /* and of change in recent messages */
  1527.   if (recent) LOCAL->dirty = T;    /* mark dirty so O flags are set */
  1528.   return fd;            /* return the winnage */
  1529. }
  1530.  
  1531. /* Berkeley search for end of message
  1532.  * Accepts: start of message
  1533.  *        start of new data
  1534.  *        size of new data
  1535.  * Returns: pointer to start of new message if one found
  1536.  */
  1537.  
  1538. #define Word unsigned long
  1539.  
  1540. char *bezerk_eom (char *som,char *sod,long i)
  1541. {
  1542.   char *s = sod;        /* find start of line in current message */
  1543.   char *t;
  1544.   int ti,zn;
  1545.   union {
  1546.     unsigned long wd;
  1547.     char ch[9];
  1548.   } wdtest;
  1549.   strcpy (wdtest.ch,"AAAA1234");/* constant for word testing */
  1550.   while ((s > som) && *s-- != '\n');
  1551.   if (wdtest.wd != 0x41414141) {/* not a 32-bit word machine? */
  1552.     while (s = strstr (s,"\nFrom ")) if (s++ && VALID (s,t,ti,zn)) return s;
  1553.   }
  1554.   else {            /* can do it faster this way */
  1555.     register Word m = 0x0a0a0a0a;
  1556.     while ((long) s & 3)    /* any characters before word boundary? */
  1557.       if ((*s++ == '\n') && s[0] == 'F' && VALID (s,t,ti,zn)) return s;
  1558.     i = (sod + i) - s;        /* total number of tries */
  1559.     do {            /* fast search for newline */
  1560.       if (0x80808080 & (0x01010101 + (0x7f7f7f7f & ~(m ^ *(Word *) s)))) {
  1561.                 /* interesting word, check it closer */
  1562.     if (*s++ == '\n' && s[0] == 'F' && VALID (s,t,ti,zn)) return s;
  1563.     else if (*s++ == '\n' && s[0] == 'F' && VALID (s,t,ti,zn)) return s;
  1564.     else if (*s++ == '\n' && s[0] == 'F' && VALID (s,t,ti,zn)) return s;
  1565.     else if (*s++ == '\n' && s[0] == 'F' && VALID (s,t,ti,zn)) return s;
  1566.       }
  1567.       else s += 4;        /* try next word */
  1568.       i -= 4;            /* count a word checked */
  1569.     } while (i > 24);        /* continue until end of plausible string */
  1570.   }
  1571.   return NIL;
  1572. }
  1573.  
  1574. /* Berkeley extend mailbox to reserve worst-case space for expansion
  1575.  * Accepts: MAIL stream
  1576.  *        file descriptor
  1577.  *        error string
  1578.  * Returns: T if extend OK and have gone critical, NIL if should abort
  1579.  */
  1580.  
  1581. int bezerk_extend (MAILSTREAM *stream,int fd,char *error)
  1582. {
  1583.   struct stat sbuf;
  1584.   FILECACHE *m;
  1585.   char tmp[MAILTMPLEN];
  1586.   int i,ok;
  1587.   long f;
  1588.   char *s;
  1589.   int retry;
  1590.                 /* calculate estimated size of mailbox */
  1591.   for (i = 0,f = 0; i < stream->nmsgs; i++) {
  1592.     m = LOCAL->msgs[i];        /* get cache pointer */
  1593.     f += (m->header - m->internal) + m->headersize + sizeof (STATUS) +
  1594.       m->bodysize + 1;        /* update guesstimate */
  1595.     }
  1596.   mm_critical (stream);        /* go critical */
  1597.                 /* return now if file large enough */
  1598.   if (f <= LOCAL->filesize) return T;
  1599.   s = (char *) fs_get (f -= LOCAL->filesize);
  1600.   memset (s,0,f);        /* get a block of nulls */
  1601.                 /* get to end of file */
  1602.   lseek (fd,LOCAL->filesize,L_SET);
  1603.   do {
  1604.     retry = NIL;        /* no retry yet */
  1605.     if (!(ok = (write (fd,s,f) >= 0))) {
  1606.       i = errno;        /* note error before doing ftruncate */
  1607.                 /* restore prior file size */
  1608.       ftruncate (fd,LOCAL->filesize);
  1609.       fsync (fd);        /* is this necessary? */
  1610.       fstat (fd,&sbuf);        /* now get updated file time */
  1611.       LOCAL->filetime = sbuf.st_mtime;
  1612.                 /* punt if that's what main program wants */
  1613.       if (mm_diskerror (stream,i,NIL)) {
  1614.     mm_nocritical (stream);    /* exit critical */
  1615.     sprintf (tmp,"%s: %s",error,strerror (i));
  1616.     mm_notify (stream,tmp,WARN);
  1617.       }
  1618.       else retry = T;        /* set to retry */
  1619.     }
  1620.   } while (retry);        /* repeat if need to try again */
  1621.   fs_give ((void **) &s);    /* flush buffer of nulls */
  1622.   return ok;            /* return status */
  1623. }
  1624.  
  1625. /* Berkeley save mailbox
  1626.  * Accepts: MAIL stream
  1627.  *        mailbox file descriptor
  1628.  *
  1629.  * Mailbox must be readwrite and locked for exclusive access.
  1630.  */
  1631.  
  1632. void bezerk_save (MAILSTREAM *stream,int fd)
  1633. {
  1634.   struct stat sbuf;
  1635.   struct iovec iov[16];
  1636.   int iovc;
  1637.   long i;
  1638.   int e;
  1639.   int retry;
  1640.   do {                /* restart point if failure */
  1641.     retry = NIL;        /* no need to retry yet */
  1642.                 /* start at beginning of file */
  1643.     lseek (fd,LOCAL->filesize = 0,L_SET);
  1644.                 /* loop through all messages */
  1645.     for (i = 1,iovc = 0; i <= stream->nmsgs; i++) {
  1646.                 /* set up iov's for this message */
  1647.       bezerk_write_message (iov,&iovc,LOCAL->msgs[i-1]);
  1648.                 /* filled up iovec or end of messages? */
  1649.       if ((iovc == 16) || (i == stream->nmsgs)) {
  1650.                 /* write messages */
  1651.     if ((e = writev (fd,iov,iovc)) < 0) {
  1652.       sprintf (LOCAL->buf,"Unable to rewrite mailbox: %s",
  1653.            strerror (e = errno));
  1654.       mm_log (LOCAL->buf,WARN);
  1655.       mm_diskerror (stream,e,T);
  1656.       retry = T;        /* must retry */
  1657.       break;        /* abort this particular try */
  1658.     }
  1659.     else {            /* won */
  1660.       iovc = 0;        /* restart iovec */
  1661.       LOCAL->filesize += e;    /* count these bytes in data */
  1662.     }
  1663.       }
  1664.     }
  1665.   } while (retry);        /* repeat if need to try again */
  1666.   fsync (fd);            /* make sure the disk has the update */
  1667.                 /* nuke any cruft after that */
  1668.   ftruncate (fd,LOCAL->filesize);
  1669.   fsync (fd);            /* is this necessary? */
  1670.   fstat (fd,&sbuf);        /* now get updated file time */
  1671.   LOCAL->filetime = sbuf.st_mtime;
  1672.   LOCAL->dirty = NIL;        /* stream no longer dirty */
  1673.   mm_nocritical (stream);    /* exit critical */
  1674. }
  1675.  
  1676. /* Berkeley copy messages
  1677.  * Accepts: MAIL stream
  1678.  *        mailbox name
  1679.  * Returns: T if copy successful else NIL
  1680.  */
  1681.  
  1682. int bezerk_copy_messages (MAILSTREAM *stream,char *mailbox)
  1683. {
  1684.   char file[MAILTMPLEN];
  1685.   char lock[MAILTMPLEN];
  1686.   struct iovec iov[16];
  1687.   int fd,iovc;
  1688.   struct stat sbuf;
  1689.   long i;
  1690.   int ok = T;
  1691.                 /* make sure valid mailbox */
  1692.   if (!bezerk_isvalid (mailbox,file)) {
  1693.     sprintf (LOCAL->buf,"Not a Berkeley-format mailbox: %s",mailbox);
  1694.     mm_log (LOCAL->buf,ERROR);
  1695.     return NIL;
  1696.   }
  1697.   if ((fd = bezerk_lock (bezerk_file (file,mailbox),O_WRONLY|O_APPEND|O_CREAT,
  1698.              S_IREAD|S_IWRITE,lock,LOCK_EX)) < 0) {
  1699.     sprintf (LOCAL->buf,"Can't open destination mailbox: %s",strerror (errno));
  1700.     mm_log (LOCAL->buf,ERROR);
  1701.     return NIL;
  1702.   }
  1703.   mm_critical (stream);        /* go critical */
  1704.   fstat (fd,&sbuf);        /* get current file size */
  1705.                 /* write all requested messages to mailbox */
  1706.   for (i = 1,iovc = 0; ok && i <= stream->nmsgs; i++) {
  1707.                 /* set up iov's if message selected */
  1708.     if (mail_elt (stream,i)->sequence)
  1709.       bezerk_write_message (iov,&iovc,LOCAL->msgs[i - 1]);
  1710.                 /* filled up iovec or end of messages? */
  1711.     if (iovc && ((iovc == 16) || (i == stream->nmsgs))) {
  1712.       if (ok = (writev (fd,iov,iovc) >= 0)) iovc = 0;
  1713.       else {
  1714.     sprintf (LOCAL->buf,"Message copy failed: %s",strerror (errno));
  1715.     mm_log (LOCAL->buf,ERROR);
  1716.     ftruncate (fd,sbuf.st_size);
  1717.     break;
  1718.       }
  1719.     }
  1720.   }
  1721.   fsync (fd);            /* force out the update */
  1722.   bezerk_unlock (fd,NIL,lock);    /* unlock and close mailbox */
  1723.   mm_nocritical (stream);    /* release critical */
  1724.   return ok;            /* return whether or not succeeded */
  1725. }
  1726.  
  1727. /* Berkeley write message to mailbox
  1728.  * Accepts: I/O vector
  1729.  *        I/O vector index
  1730.  *        local cache for this message
  1731.  *
  1732.  * This routine is the reason why the local cache has a copy of the status.
  1733.  * We can be called to dump out the mailbox as part of a stream recycle, since
  1734.  * we don't write out the mailbox when flags change and hence an update may be
  1735.  * needed.  However, at this point the elt has already become history, so we
  1736.  * can't use any information other than what is local to us.
  1737.  */
  1738.  
  1739. void bezerk_write_message (struct iovec iov[],int *i,FILECACHE *m)
  1740. {
  1741.   iov[*i].iov_base =m->internal;/* pointer/counter to headers */
  1742.                 /* length of internal + message headers */
  1743.   iov[*i].iov_len = (m->header + m->headersize) - m->internal;
  1744.                 /* suppress extra newline if present */
  1745.   if ((iov[*i].iov_base)[iov[*i].iov_len - 2] == '\n') iov[(*i)++].iov_len--;
  1746.   else (*i)++;            /* unlikely but... */
  1747.   iov[*i].iov_base = m->status;    /* pointer/counter to status */
  1748.   iov[(*i)++].iov_len = strlen (m->status);
  1749.   iov[*i].iov_base = m->body;    /* pointer/counter to text body */
  1750.   iov[(*i)++].iov_len = m->bodysize;
  1751.   iov[*i].iov_base = "\n";    /* pointer/counter to extra newline */
  1752.   iov[(*i)++].iov_len = 1;
  1753. }
  1754.  
  1755. /* Berkeley update status string
  1756.  * Accepts: destination string to write
  1757.  *        message cache entry
  1758.  */
  1759.  
  1760. void bezerk_update_status (char *status,MESSAGECACHE *elt)
  1761. {
  1762.   /* This used to be an sprintf(), but thanks to certain cretinous C libraries
  1763.      with horribly slow implementations of sprintf() I had to change it to this
  1764.      mess.  At least it should be fast. */
  1765.   char *t = status + 8;
  1766.   status[0] = 'S'; status[1] = 't'; status[2] = 'a'; status[3] = 't';
  1767.   status[4] = 'u'; status[5] = 's'; status[6] = ':';  status[7] = ' ';
  1768.   if (elt->seen) *t++ = 'R'; *t++ = 'O'; *t++ = '\n';
  1769.   *t++ = 'X'; *t++ = '-'; *t++ = 'S'; *t++ = 't'; *t++ = 'a'; *t++ = 't';
  1770.   *t++ = 'u'; *t++ = 's'; *t++ = ':'; *t++ = ' ';
  1771.   if (elt->deleted) *t++ = 'D'; if (elt->flagged) *t++ = 'F';
  1772.   if (elt->answered) *t++ = 'A';
  1773.   *t++ = '\n'; *t++ = '\n'; *t++ = '\0';
  1774. }
  1775.  
  1776. /* Parse flag list
  1777.  * Accepts: MAIL stream
  1778.  *        flag list as a character string
  1779.  * Returns: flag command list
  1780.  */
  1781.  
  1782.  
  1783. short bezerk_getflags (MAILSTREAM *stream,char *flag)
  1784. {
  1785.   char *t;
  1786.   short f = 0;
  1787.   short i,j;
  1788.   if (flag && *flag) {        /* no-op if no flag string */
  1789.                 /* check if a list and make sure valid */
  1790.     if ((i = (*flag == '(')) ^ (flag[strlen (flag)-1] == ')')) {
  1791.       mm_log ("Bad flag list",ERROR);
  1792.       return NIL;
  1793.     }
  1794.                 /* copy the flag string w/o list construct */
  1795.     strncpy (LOCAL->buf,flag+i,(j = strlen (flag) - (2*i)));
  1796.     LOCAL->buf[j] = '\0';
  1797.     t = ucase (LOCAL->buf);    /* uppercase only from now on */
  1798.  
  1799.     while (*t) {        /* parse the flags */
  1800.       if (*t == '\\') {        /* system flag? */
  1801.     switch (*++t) {        /* dispatch based on first character */
  1802.     case 'S':        /* possible \Seen flag */
  1803.       if (t[1] == 'E' && t[2] == 'E' && t[3] == 'N') i = fSEEN;
  1804.       t += 4;        /* skip past flag name */
  1805.       break;
  1806.     case 'D':        /* possible \Deleted flag */
  1807.       if (t[1] == 'E' && t[2] == 'L' && t[3] == 'E' && t[4] == 'T' &&
  1808.           t[5] == 'E' && t[6] == 'D') i = fDELETED;
  1809.       t += 7;        /* skip past flag name */
  1810.       break;
  1811.     case 'F':        /* possible \Flagged flag */
  1812.       if (t[1] == 'L' && t[2] == 'A' && t[3] == 'G' && t[4] == 'G' &&
  1813.           t[5] == 'E' && t[6] == 'D') i = fFLAGGED;
  1814.       t += 7;        /* skip past flag name */
  1815.       break;
  1816.     case 'A':        /* possible \Answered flag */
  1817.       if (t[1] == 'N' && t[2] == 'S' && t[3] == 'W' && t[4] == 'E' &&
  1818.           t[5] == 'R' && t[6] == 'E' && t[7] == 'D') i = fANSWERED;
  1819.       t += 8;        /* skip past flag name */
  1820.       break;
  1821.     default:        /* unknown */
  1822.       i = 0;
  1823.       break;
  1824.     }
  1825.                 /* add flag to flags list */
  1826.     if (i && ((*t == '\0') || (*t++ == ' '))) f |= i;
  1827.     else {            /* bitch about bogus flag */
  1828.       mm_log ("Unknown system flag",ERROR);
  1829.       return NIL;
  1830.     }
  1831.       }
  1832.       else {            /* no user flags yet */
  1833.     mm_log ("Unknown flag",ERROR);
  1834.     return NIL;
  1835.       }
  1836.     }
  1837.   }
  1838.   return f;
  1839. }
  1840.  
  1841. /* Search support routines
  1842.  * Accepts: MAIL stream
  1843.  *        message number
  1844.  *        pointer to additional data
  1845.  * Returns: T if search matches, else NIL
  1846.  */
  1847.  
  1848.  
  1849. char bezerk_search_all (MAILSTREAM *stream,long msgno,char *d,long n)
  1850. {
  1851.   return T;            /* ALL always succeeds */
  1852. }
  1853.  
  1854.  
  1855. char bezerk_search_answered (MAILSTREAM *stream,long msgno,char *d,long n)
  1856. {
  1857.   return mail_elt (stream,msgno)->answered ? T : NIL;
  1858. }
  1859.  
  1860.  
  1861. char bezerk_search_deleted (MAILSTREAM *stream,long msgno,char *d,long n)
  1862. {
  1863.   return mail_elt (stream,msgno)->deleted ? T : NIL;
  1864. }
  1865.  
  1866.  
  1867. char bezerk_search_flagged (MAILSTREAM *stream,long msgno,char *d,long n)
  1868. {
  1869.   return mail_elt (stream,msgno)->flagged ? T : NIL;
  1870. }
  1871.  
  1872.  
  1873. char bezerk_search_keyword (MAILSTREAM *stream,long msgno,char *d,long n)
  1874. {
  1875.   return NIL;            /* keywords not supported yet */
  1876. }
  1877.  
  1878.  
  1879. char bezerk_search_new (MAILSTREAM *stream,long msgno,char *d,long n)
  1880. {
  1881.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1882.   return (elt->recent && !elt->seen) ? T : NIL;
  1883. }
  1884.  
  1885. char bezerk_search_old (MAILSTREAM *stream,long msgno,char *d,long n)
  1886. {
  1887.   return mail_elt (stream,msgno)->recent ? NIL : T;
  1888. }
  1889.  
  1890.  
  1891. char bezerk_search_recent (MAILSTREAM *stream,long msgno,char *d,long n)
  1892. {
  1893.   return mail_elt (stream,msgno)->recent ? T : NIL;
  1894. }
  1895.  
  1896.  
  1897. char bezerk_search_seen (MAILSTREAM *stream,long msgno,char *d,long n)
  1898. {
  1899.   return mail_elt (stream,msgno)->seen ? T : NIL;
  1900. }
  1901.  
  1902.  
  1903. char bezerk_search_unanswered (MAILSTREAM *stream,long msgno,char *d,long n)
  1904. {
  1905.   return mail_elt (stream,msgno)->answered ? NIL : T;
  1906. }
  1907.  
  1908.  
  1909. char bezerk_search_undeleted (MAILSTREAM *stream,long msgno,char *d,long n)
  1910. {
  1911.   return mail_elt (stream,msgno)->deleted ? NIL : T;
  1912. }
  1913.  
  1914.  
  1915. char bezerk_search_unflagged (MAILSTREAM *stream,long msgno,char *d,long n)
  1916. {
  1917.   return mail_elt (stream,msgno)->flagged ? NIL : T;
  1918. }
  1919.  
  1920.  
  1921. char bezerk_search_unkeyword (MAILSTREAM *stream,long msgno,char *d,long n)
  1922. {
  1923.   return T;            /* keywords not supported yet */
  1924. }
  1925.  
  1926.  
  1927. char bezerk_search_unseen (MAILSTREAM *stream,long msgno,char *d,long n)
  1928. {
  1929.   return mail_elt (stream,msgno)->seen ? NIL : T;
  1930. }
  1931.  
  1932. char bezerk_search_before (MAILSTREAM *stream,long msgno,char *d,long n)
  1933. {
  1934.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1935.   return (char) ((long) ((elt->year << 9) + (elt->month << 5) + elt->day) < n);
  1936. }
  1937.  
  1938.  
  1939. char bezerk_search_on (MAILSTREAM *stream,long msgno,char *d,long n)
  1940. {
  1941.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1942.   return (char) (((elt->year << 9) + (elt->month << 5) + elt->day) == n);
  1943. }
  1944.  
  1945.  
  1946. char bezerk_search_since (MAILSTREAM *stream,long msgno,char *d,long n)
  1947. {
  1948.                 /* everybody interprets "since" as .GE. */
  1949.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1950.   return (char)((long) ((elt->year << 9) + (elt->month << 5) + elt->day) >= n);
  1951. }
  1952.  
  1953.  
  1954. char bezerk_search_body (MAILSTREAM *stream,long msgno,char *d,long n)
  1955. {
  1956.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  1957.   return search (m->body,m->bodysize,d,n);
  1958. }
  1959.  
  1960.  
  1961. char bezerk_search_subject (MAILSTREAM *stream,long msgno,char *d,long n)
  1962. {
  1963.   char *s = bezerk_fetchstructure (stream,msgno,NIL)->subject;
  1964.   return s ? search (s,strlen (s),d,n) : NIL;
  1965. }
  1966.  
  1967.  
  1968. char bezerk_search_text (MAILSTREAM *stream,long msgno,char *d,long n)
  1969. {
  1970.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  1971.   return search (m->header,m->headersize,d,n) ||
  1972.     bezerk_search_body (stream,msgno,d,n);
  1973. }
  1974.  
  1975. char bezerk_search_bcc (MAILSTREAM *stream,long msgno,char *d,long n)
  1976. {
  1977.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1978.                 /* get text for address */
  1979.   rfc822_write_address (LOCAL->buf,
  1980.             bezerk_fetchstructure (stream,msgno,NIL)->bcc);
  1981.   return search (LOCAL->buf,strlen (LOCAL->buf),d,n);
  1982. }
  1983.  
  1984.  
  1985. char bezerk_search_cc (MAILSTREAM *stream,long msgno,char *d,long n)
  1986. {
  1987.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1988.                 /* get text for address */
  1989.   rfc822_write_address (LOCAL->buf,
  1990.             bezerk_fetchstructure (stream,msgno,NIL)->cc);
  1991.   return search (LOCAL->buf,strlen (LOCAL->buf),d,n);
  1992. }
  1993.  
  1994.  
  1995. char bezerk_search_from (MAILSTREAM *stream,long m,char *d,long n)
  1996. {
  1997.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1998.                 /* get text for address */
  1999.   rfc822_write_address (LOCAL->buf,bezerk_fetchstructure (stream,m,NIL)->from);
  2000.   return search (LOCAL->buf,strlen (LOCAL->buf),d,n);
  2001. }
  2002.  
  2003.  
  2004. char bezerk_search_to (MAILSTREAM *stream,long msgno,char *d,long n)
  2005. {
  2006.   LOCAL->buf[0] = '\0';        /* initially empty string */
  2007.                 /* get text for address */
  2008.   rfc822_write_address (LOCAL->buf,
  2009.             bezerk_fetchstructure (stream,msgno,NIL)->to);
  2010.   return search (LOCAL->buf,strlen (LOCAL->buf),d,n);
  2011. }
  2012.  
  2013. /* Search parsers */
  2014.  
  2015.  
  2016. /* Parse a date
  2017.  * Accepts: function to return
  2018.  *        pointer to date integer to return
  2019.  * Returns: function to return
  2020.  */
  2021.  
  2022. search_t bezerk_search_date (search_t f,long *n)
  2023. {
  2024.   long i;
  2025.   char *s;
  2026.   MESSAGECACHE elt;
  2027.                 /* parse the date and return fn if OK */
  2028.   return (bezerk_search_string (f,&s,&i) && mail_parse_date (&elt,s) &&
  2029.       (*n = (elt.year << 9) + (elt.month << 5) + elt.day)) ? f : NIL;
  2030. }
  2031.  
  2032. /* Parse a flag
  2033.  * Accepts: function to return
  2034.  *        pointer to string to return
  2035.  * Returns: function to return
  2036.  */
  2037.  
  2038. search_t bezerk_search_flag (search_t f,char **d)
  2039. {
  2040.                 /* get a keyword, return if OK */
  2041.   return (*d = strtok (NIL," ")) ? f : NIL;
  2042. }
  2043.  
  2044.  
  2045. /* Parse a string
  2046.  * Accepts: function to return
  2047.  *        pointer to string to return
  2048.  *        pointer to string length to return
  2049.  * Returns: function to return
  2050.  */
  2051.  
  2052.  
  2053. search_t bezerk_search_string (search_t f,char **d,long *n)
  2054. {
  2055.   char *c = strtok (NIL,"");    /* remainder of criteria */
  2056.   if (c) {            /* better be an argument */
  2057.     switch (*c) {        /* see what the argument is */
  2058.     case '\0':            /* catch bogons */
  2059.     case ' ':
  2060.       return NIL;
  2061.     case '"':            /* quoted string */
  2062.       if (!(strchr (c+1,'"') && (*d = strtok (c,"\"")) && (*n = strlen (*d))))
  2063.     return NIL;
  2064.       break;
  2065.     case '{':            /* literal string */
  2066.       *n = strtol (c+1,&c,10);    /* get its length */
  2067.       if (*c++ != '}' || *c++ != '\015' || *c++ != '\012' ||
  2068.       *n > strlen (*d = c)) return NIL;
  2069.       c[*n] = '\255';        /* write new delimiter */
  2070.       strtok (c,"\255");    /* reset the strtok mechanism */
  2071.       break;
  2072.     default:            /* atomic string */
  2073.       *n = strlen (*d = strtok (c," "));
  2074.       break;
  2075.     }
  2076.     return f;
  2077.   }
  2078.   else return NIL;
  2079. }
  2080.